<?php

namespace App\Model\Member;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\DB;
use Eloquent;
use Mockery\CountValidator\Exception;

class Store extends Model
{
    /**
     * The table associated with the model.
     *
     * @var string
     */
    protected $table = 'store';

    /**
     * Indicates if the model should be timestamped.
     *
     * @var bool
     */
    public $timestamps = false;

    /**
     *
     * 查询商户绑定的会员ID
     *
     * @param $id
     * @return null
     */
    public static function getBind($id)
    {
        if (self::find($id)) {
            $user = User::where('store_id', $id)->first();
            if (!empty($user->id)) return  $user->id;
        }
        return null;
    }

    /**
     *
     * 给商户绑定会员
     *
     * @param $id
     * @param $member
     * @return bool
     */
    public static function setBind($id, $member)
    {
        $store = self::find($id);
        if (!$store) {
            return false;
        }
        $user = User::find($member);
        if (!$user) {
            return false;
        }
        DB::beginTransaction();
        $user->store_id = $id;
        if (!$user->save()) {
            DB::rollBack();
            return false;
        }
        try {
            self::where('user_id', $member)->update([ 'user_id' => 0]);
        }
        catch (Exception $e){
            DB::rollBack();
            return false;
        }
        $store->user_id = $member;
        if (!$store->save()) {
            DB::rollBack();
            return false;
        }
        DB::commit();
        return true;
    }

    /**
     *
     * 解除商户绑定的会员
     *
     * @param $id
     * @return bool
     */
    public static function unBind($id)
    {
        $store = self::find($id);
        if ($store && !empty($store->user_id)) {
            DB::beginTransaction();
            $userID = $store->user_id;
            $store->user_id = 0;
            if ($store->save()) {
                $user = User::find($userID);
                if ($user) {
                    $user->store_id = 0;
                    if ($user->save()) {
                        DB::commit();
                        return true;
                    }
                } else {
                    DB::commit();
                    return true;
                }
            }
            DB::rollBack();
        }
        return false;
    }

    /**
     *
     * 获取店铺名称（默认为虚拟店铺） update by liudong 传一个比较值 20160818
     *
     * @param string $con
     * @return array
     */
    public static function virtualName($con = '=')
    {
        $store = [];
        $result = self::where('user_id',$con, 0)->get();
        foreach ($result as $key => $val) {
            $store[$val->id] = $val->title;
        }
        return $store;
    }
}